﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSP.Bll.CommonBll;
using CSP.Bll.IObjectBlls;
using CSP.Dao.IObjectDaos.CSP;
using CSP.Common.Factories;
using CSP.Dao;
using CSP.Model.CSP;
using System.Collections.ObjectModel;
using System.Web;
using CSP.Common.Providers;
using System.IO;
using CSP.Model.CSPBBS;

namespace CSP.Bll.ObjectBlls
{
    /// <summary>
    /// 认证
    /// </summary>
    public class AuthenticationBll : CSPCommonBll, IAuthenticationBll
    {
        /// <summary>
        /// 缓存键值
        /// </summary>
        private const string CACHEKEY = "Authentication_";

        private IAuthenticationDao _authenticationDao;

        private IUserInfoBll _userInfoBll;

        public AuthenticationBll()
        {
            _userInfoBll = CSPBllFactory.GetInstance().GetUserInfoBll();
            _cacheProvider = CachedProviderFactory.GetMemCachedProvider();
            _authenticationDao = CSPDaoFactory.GetInstance().GetAuthenticationDao();
        }


        public ICollection<Authentication> GetByUser(string userName)
        {
            string cacheKey = CACHEKEY + userName.ToString();
            ICollection<Authentication> authentications = _cacheProvider.GetData<Collection<Authentication>>(cacheKey);
            if (authentications == null)
            {
                authentications = _authenticationDao.GetByUser(userName);
                _cacheProvider.AddData(cacheKey, authentications, DateTime.Now.AddHours(1));
            }
            return authentications;
        }

        public Model.CSP.Authentication GetDataById(int id)
        {
            //To Do
            throw new NotImplementedException();
        }

        public ICollection<Model.CSP.Authentication> GeDatatByIds(int[] Ids)
        {
            //To Do
            throw new NotImplementedException();
        }

        public Authentication Add(Authentication authentication, HttpPostedFile file)
        {

            string cacheKey = CACHEKEY + authentication.Username;

            //上传图片获取图片信息
            ImageProviderFactory imageFactory = ImageProviderFactory.GetInstance();
            imageFactory.LWidth = 600;
            ImageProvider imageProvider = imageFactory.UploadForThumbnail(file);
            int indexFileName = imageProvider.New_FileName.LastIndexOf("/");
            authentication.Filepath = imageProvider.SavePath;
            authentication.Filename = imageProvider.New_FileName.Substring(indexFileName + 1);

            //如果是个人或机构认证，删除以前的认证并且在用户基本信息中将个人或机构认证状态置为审核中...
            if (authentication.CertificateType == 0 || authentication.CertificateType == 1)
            {
                RemoveByUserAndCertificateType(authentication.Username, authentication.CertificateType);
                AuditingForUserBasic(authentication);
            }

            _authenticationDao.Add(authentication);
            _cacheProvider.Remove(cacheKey);
            return authentication;
        }

        public void Add(Model.CSP.Authentication obj)
        {
            if (obj == null)
            {
                throw new Exception("obj Can't be null");
            }
            _authenticationDao.Add(obj);

        }

        public void Update(Model.CSP.Authentication obj)
        {
            string cacheKey = CACHEKEY + obj.Username.ToString();
            _authenticationDao.Update(obj);

            _cacheProvider.Remove(cacheKey);
        }

        public void DeleteById(int id)
        {
            var authentication = _authenticationDao.DeleteById(id);

            string cacheKey = CACHEKEY + authentication.Username.ToString();

            _cacheProvider.Remove(cacheKey);
            RemoveFileByAuthentication(authentication);
        }

        public void RefreshCache()
        {
            //To Do
            throw new NotImplementedException();
        }



        public Authentication GetByIdAndUser(int id, string userName)
        {
            Authentication authentication = _authenticationDao.GetByIdAndUser(id, userName);
            RemoveFileByAuthentication(authentication);
            return authentication;
        }

        /// <summary>
        /// 根据用户和认证类型删除数据
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="certificateType"></param>
        private void RemoveByUserAndCertificateType(string userName, int certificateType)
        {
            Authentication authenication = _authenticationDao.RemoveByUserAndCertificateType(userName, certificateType);

        }

        public Authentication RemoveByIdAndUser(int id, string userName)
        {
            Authentication authenication = _authenticationDao.RemoveByIdAndUser(id, userName);
            return authenication;
        }

        /// <summary>
        /// 在UserBasic中审核-审核状态
        /// </summary>
        /// <param name="authentication"></param>
        private void AuditingForUserBasic(Authentication authentication)
        {
            Member member = _userInfoBll.GetUser(authentication.Username, false);
            //个人认证
            if (authentication.CertificateType == 0)
            {
                member.UserBasic.PersonalAuthentication = 1;
            }
            //企业认证
            else if (authentication.CertificateType == 1)
            {
                member.UserBasic.EnterpriseAuthentication = 1;
            }
            _userInfoBll.Update(member.UserBasic);

        }

        private void RemoveFileByAuthentication(Authentication authenication)
        {
            if (authenication != null)
            {
                string filePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + authenication.Filepath + authenication.Filename;
                string s_filePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + authenication.Filepath + "s_" + authenication.Filename;
                File.Delete(filePath);
                File.Delete(s_filePath);
            }
        }
    }
}
